import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  ElMessageBox
} from "element-plus";
import {
  getWarehouseListApi,
  createWarehouseApi,
  updateWarehouseApi,
  delWarehouseApi,
  getWarehouseShowApi,
  updateWarehouseStatusApi
} from "@/api/warehouse";

export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 10,
    departmentId: "",
    name: "",
    
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "warehouseId"
    },
    {
      label: "仓库名称",
      prop: "name"
    },
    {
      label: "仓库编码",
      prop: "code"
    },
    {
      label: "子车X轴起始坐标",
      prop: "carStartXPos"
    },
    {
      label: "子车Y轴起始坐标",
      prop: "carStartYPos"
    },
	{
	  label: "子车X轴结束坐标",
	  prop: "carEndXPos"
	},
	{
	  label: "子车Y轴结束坐标",
	  prop: "carEndYPos"
	},
    {
      label: "子车X增大方向为右",
      prop: "carXIncrRight",
      formatter: (row) => {
      	return row.carXIncrRight === 0?'否':'是'
      }
    },
	{
	  label: "子车Y增大方向为右",
	  prop: "carYIncrRight",
	  formatter: (row) => {
	  	return row.carYIncrRight === 0?'否':'是'
	  }
	},
	{
	  label: "AVG地图方向",
	  prop: "agvMapDirectFormat",
	  // formatter: (row) => {
	  // 	return row.agvMapDirect === 1?'上':row.agvMapDirect === 2?'下':row.agvMapDirect === 3?'左':'右'
	  // }
	},
	{
	  label: "状态",
	  prop: "status",
	  cellRenderer: scope => (
	  	<el-switch
	  	  size={scope.props.size === "small" ? "small" : "default"}
	  	  v-model={scope.row.status}
	  	  active-value={1}
	  	  inactive-value={2}
	  	  active-text="启用"
	  	  inactive-text="禁用"
	  	  inline-prompt
	  	  onClick={() => switchStatus(scope as any)}
	  	/>
	  )
	},
    // {
    //   label: "操作人",
    //   prop: "operateName"
    // },
    // {
    //   label: "创建时间",
    //   prop: "createdAt"
    // },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getWarehouseListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getWarehouseListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getWarehouseListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.per_page;
    pagination.currentPage = result.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }
	/** 启用/停用*/
	function switchStatus ({ row }) {
		ElMessageBox.confirm(
		  `确认要<strong>${
			row.status === 2 ? "禁用" : "启用"
		  }</strong><strong style='color:var(--el-color-primary)'>${
			row.name
		  }</strong>仓库吗?`,
		  "系统提示",
		  {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
			dangerouslyUseHTMLString: true,
			draggable: true
		  }
		)
		  .then(async() => {
			let params = {
				warehouseId: row.warehouseId,
				status: row.status === 2 ? 2 : 1
			}
			const res = await updateWarehouseStatusApi(params);
			if(res.code !== 200) {
				message(res.msg ?? "操作失败,请联系管理员", {
				  type: "error"
				});
				return
			}
			onSearch()
			
			message("已成功修改用户状态", {
				type: "success"
			});
		  })
		  .catch(() => {
			row.status === 2 ? (row.status = 1) : (row.status = 2);
		  });
	}
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function formatHigherDeptOptions(treeList: any) {
      // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
      if (!treeList || !treeList.length) return;
      const newTreeList = [];
      for (let i = 0; i < treeList.length; i++) {
        treeList[i].disabled = treeList[i].status === 0 ? true : false;
        formatHigherDeptOptions(treeList[i].children);
        newTreeList.push(treeList[i]);
      }
      return newTreeList;
    }
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		carYIncrRight: 1,
		carXIncrRight: 1
      };
    } else {
      const res = await getWarehouseShowApi({ warehouseId: row.warehouseId });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline.value = {
        title: "修改",
        warehouseId: res?.result?.warehouseId ?? "",
        name: res?.result?.name ?? "",
        code: res?.result?.code ?? "",
        carXIncrRight: res?.result?.carXIncrRight ?? "",
        carYIncrRight: res?.result?.carYIncrRight ?? "",
        carStartXPos: res?.result?.carStartXPos ?? "",
        carStartYPos: res?.result?.carStartYPos ?? "",
        carEndXPos: res?.result?.carEndXPos ?? "",
        carEndYPos: res?.result?.carEndYPos ?? "",
        agvMapDirect: res?.result?.agvMapDirect ?? "",
      };
	  
    }
    addDialog({
      title: `${title}信息`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createWarehouseApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateWarehouseApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
	
  });

  function handleDelete(row) {
    delWarehouseApi({ warehouseId: row.warehouseId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  function confirmStatus() {
    alert("审核通过");
  }
  function refusedStatus() {
    alert("审核拒绝");
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    confirmStatus,
    refusedStatus
  };
}
